
package com.zff.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zff.dao.XspxGaojianInfoDao;
import com.zff.dao.XstWxUserDao;
import com.zff.dao.YsjGaojainDao;
import com.zff.entity.XspxGaojianInfo;
import com.zff.entity.XstWxUser;
import com.zff.entity.YsjGaojain;
import com.zff.service.XstWxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class XstWxuserServiceImpl implements XstWxUserService {

    @Autowired
    private XstWxUserDao xstWxUserDao;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private XspxGaojianInfoDao xspxGaojianInfoDao;
    @Autowired
    private YsjGaojainDao ysjGaojainDao;


/**
     * 新增微信用户
     * @param userInfo
     * @return
     */

    public List<XstWxUser> insterUser(JSONObject userInfo){
        XstWxUser wxUser = new XstWxUser();
        wxUser.setUnionId((String) userInfo.get("unionid"));
        wxUser.setOpenId((String) userInfo.get("openid"));
        wxUser.setNickname((String) userInfo.get("nickname"));
        wxUser.setHeadimgRul((String)userInfo.get("headimgurl"));
        wxUser.setAid(2);
        Integer insert = xstWxUserDao.insert(wxUser);
        if(insert>0){
            HashMap<String, Object> map = new HashMap<>();
            String openid = (String) userInfo.get("openid");
            String unionid = (String) userInfo.get("unionid");
            map.put("openid",openid);
            map.put("unionid",unionid);
            List<XstWxUser> xstWxUsers = xstWxUserDao.selectByMap(map);
            return xstWxUsers;
        } else {
            return null;
        }
    }

    /**
     * 获取授权用户的信息
     * 先用openid来做判定，后面如果有复杂业务可以再考虑unionid做判定
     * @param userInfo
     * @return
     */
    @Override
    public Integer getUserByJson(JSONObject userInfo) {
        HashMap<String, Object> map = new HashMap<>();
        String openid = (String) userInfo.get("openid");
        String unionid = (String) userInfo.get("unionid");
        map.put("openid",openid);
        map.put("unionid",unionid);
        BoundValueOperations<String, Object> user = redisTemplate.boundValueOps(openid);
        Object o = user.get();
        Integer userId = null;
        List<XstWxUser> xstWxUsers = new ArrayList<>();
        if(o == null){//先去redis缓存中去找openid对应的对象，若缓存中没有就去数据库中找
            xstWxUsers = xstWxUserDao.selectByMap(map);
            if(xstWxUsers.size()>0){//若数据库中存在对象，将从数据库中查出的对象放入缓存中
                user.set(xstWxUsers);
                System.out.println("没有存入缓存，从数据库中取数据放入缓存，"+ xstWxUsers);
                //user.get();
                for (XstWxUser wxUser : xstWxUsers){
                    userId = wxUser.getId();
                }
            } else {//若数据库中不存在对象，则先将数据存入数据库中，在将其放入缓存中
                xstWxUsers = insterUser(userInfo);
                user.set(xstWxUsers);
                System.out.println("没有存入缓存，也没有存入数据库，先存入数据库，再存入缓存，"+ xstWxUsers);
                for (XstWxUser wxUser : xstWxUsers){
                    userId = wxUser.getId();
                }
            }
        } else {
            System.out.println("缓存中有数据，"+o);
            List<XstWxUser> list= JSON.parseArray(JSON.toJSONString(o), XstWxUser.class);
            for (XstWxUser xstWxUser : list){
                userId = xstWxUser.getId();
            }
        }

        return userId;
    }

    /**
     * 获取声明
     * @param userId
     * @return
     */
    public String getIsVoice(String userId){
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",userId);
        String isVoice = null;
        List<XstWxUser> xstWxUsers = xstWxUserDao.selectByMap(map);
        for (XstWxUser wxUser: xstWxUsers){
            isVoice = wxUser.getIsVoice();
        }
        return isVoice;
    }

    /**
     * 根据openid从缓存中获取用户数据
     * @param openid
     * @return
     */
    public List<XstWxUser> getXstUser(String openid){
        BoundValueOperations<String, Object> user = redisTemplate.boundValueOps(openid);
        Object o = user.get();
        List<XstWxUser> list= JSON.parseArray(JSON.toJSONString(o), XstWxUser.class);
        return list;
    }

    /**
     * 更新投稿用户的用户信息，更新数据库，更新缓存lw
     * @param form
     * @return
     */
    @Override
    public Integer updateUserInfo(JSONObject form) {
        String userId = (String) form.get("userId");
        int userid = Integer.parseInt(userId);
        String username = (String) form.get("username");
        String phone = (String) form.get("phone");
        String sex = (String) form.get("sex");
        String  a= (String)form.get("birthday");
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        Date birthday = null;
        try {
            birthday = fmt.parse(a);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String education = (String) form.get("education");
        String studySection = (String) form.get("studySection");
        String teacherAge = (String) form.get("teacherAge");
        String post = (String) form.get("post");
        String title = (String) form.get("title");
        String workUnit = (String) form.get("workUnit");
        Object aaa = form.get("selectedOptions");
        String address = aaa.toString();
        System.out.println("selectedOptions:"+address);
        String email = (String) form.get("email");
        String xslw = (String) form.get("xslw");
        String jxsj = (String) form.get("jxsj");
        String lwtable = (String) form.get("lwtable");
        String remarks = (String) form.get("remarks");

        String xslwname = null;

        String jxsjname = null;

        XspxGaojianInfo xspxGaojianInfo = new XspxGaojianInfo();
        xspxGaojianInfo.setUserId(userid);
        xspxGaojianInfo.setType("2");
        xspxGaojianInfo.setResultCode("待提交");
        xspxGaojianInfo.setUsername(username);
        xspxGaojianInfo.setPhone(phone);
        xspxGaojianInfo.setSex(sex);
        xspxGaojianInfo.setBirthday(birthday);
        xspxGaojianInfo.setStudySection(studySection);
        xspxGaojianInfo.setEducation(education);
        xspxGaojianInfo.setTeacherAge(teacherAge);
        xspxGaojianInfo.setPost(post);
        xspxGaojianInfo.setTitle(title);
        xspxGaojianInfo.setWorkUnit(workUnit);
        xspxGaojianInfo.setAddress(address);
        xspxGaojianInfo.setEmail(email);
        xspxGaojianInfo.setRemarks(remarks);
        xspxGaojianInfo.setXslw(xslw);
        xspxGaojianInfo.setLwtable(lwtable);
        if(xslw!=null){
            HashMap<String, Object> map = new HashMap<>();
            map.put("filePath",xslw);
            List<YsjGaojain> ysjGaojains = ysjGaojainDao.selectByMap(map);
            for (YsjGaojain gaojian: ysjGaojains){
                xslwname = gaojian.getFilename();
            }
            xspxGaojianInfo.setXslwname(xslwname);
        }

        xspxGaojianInfo.setJxsj(jxsj);

        if(jxsj!=null){
            HashMap<String, Object> map = new HashMap<>();
            map.put("filePath",jxsj);
            List<YsjGaojain> ysjGaojains = ysjGaojainDao.selectByMap(map);
            for (YsjGaojain gaojian: ysjGaojains){
                jxsjname = gaojian.getFilename();
            }
            xspxGaojianInfo.setJsxjname(jxsjname);
        }
        xspxGaojianInfo.setIsshow("1");
        //xspxGaojianInfo.setResultCode("0");
        int insert = xspxGaojianInfoDao.insert(xspxGaojianInfo);
        System.out.println("iiiii:"+insert);
        return insert;
    }

    /**
     * 更新投稿用户的用户信息，更新数据库，更新缓存cg
     * @param form
     * @return
     */
    @Override
    public Integer updateUserInfocg(JSONObject form) {
        String userId = (String) form.get("userId");
        int userid = Integer.parseInt(userId);
        String username = (String) form.get("username");
        String phone = (String) form.get("phone");
        String sex = (String) form.get("sex");
        String  a= (String)form.get("birthday");
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        Date birthday = null;
        try {
            birthday = fmt.parse(a);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String education = (String) form.get("education");
        String studySection = (String) form.get("studySection");
        String teacherAge = (String) form.get("teacherAge");
        String post = (String) form.get("post");
        String title = (String) form.get("title");
        String workUnit = (String) form.get("workUnit");
        Object aaa = form.get("selectedOptions");
        String address = aaa.toString();
        System.out.println("selectedOptions:"+address);
        String email = (String) form.get("email");
        String cgzp = (String) form.get("cgzp");
        String cgtable = (String) form.get("cgtable");
        String remarks = (String) form.get("remarks");

        String cgzpname = null;

        XspxGaojianInfo xspxGaojianInfo = new XspxGaojianInfo();
        xspxGaojianInfo.setUserId(userid);
        xspxGaojianInfo.setType("1");
        if (cgzp.length()>0 ||cgzp != null){
            xspxGaojianInfo.setResultCode("待评审");
        } else {
            xspxGaojianInfo.setResultCode("请上传作品");
        }

        xspxGaojianInfo.setUsername(username);
        xspxGaojianInfo.setPhone(phone);
        xspxGaojianInfo.setSex(sex);
        xspxGaojianInfo.setBirthday(birthday);
        xspxGaojianInfo.setStudySection(studySection);
        xspxGaojianInfo.setEducation(education);
        xspxGaojianInfo.setTeacherAge(teacherAge);
        xspxGaojianInfo.setPost(post);
        xspxGaojianInfo.setTitle(title);
        xspxGaojianInfo.setWorkUnit(workUnit);
        xspxGaojianInfo.setAddress(address);
        xspxGaojianInfo.setEmail(email);
        xspxGaojianInfo.setRemarks(remarks);
        xspxGaojianInfo.setCgzp(cgzp);
        xspxGaojianInfo.setCgtable(cgtable);
        if(cgzp!=null){
            HashMap<String, Object> map = new HashMap<>();
            map.put("filePath",cgzp);
            List<YsjGaojain> ysjGaojains = ysjGaojainDao.selectByMap(map);
            for (YsjGaojain gaojian: ysjGaojains){
                cgzpname = gaojian.getFilename();
            }
            xspxGaojianInfo.setCgzpname(cgzpname);
        }
        //xspxGaojianInfo.setResultCode("0");
        xspxGaojianInfo.setIsshow("1");
        int insert = xspxGaojianInfoDao.insert(xspxGaojianInfo);
        System.out.println("iiiii:"+insert);
        return insert;
    }

    /**
     * 完善用户信息
     * @param form
     * @return
     */
    @Override
    public Integer updateUser(JSONObject form) {
        String openid = (String) form.get("openid");
        String userId = (String) form.get("userId");
        int userid = Integer.parseInt(userId);
        String username = (String) form.get("username");
        String phone = (String) form.get("phone");
        String province = (String) form.get("province");
        String city = (String) form.get("city");
        String dist = (String) form.get("dist");
        String schoolArea = province+","+city+","+dist;
        String workUnit = (String) form.get("workUnit");
        String shippingAddress = (String) form.get("shippingAddress");
        String studySection = (String) form.get("studySection");
        XstWxUser xstWxUser = new XstWxUser();
        xstWxUser.setId(userid);
        xstWxUser.setUsername(username);
        xstWxUser.setPhone(phone);
        xstWxUser.setSchoolArea(schoolArea);
        xstWxUser.setWorkUnit(workUnit);
        xstWxUser.setShippingAddress(shippingAddress);
        xstWxUser.setStudySection(studySection);
        int count = xstWxUserDao.updateById(xstWxUser);
        HashMap<String, Object> map = new HashMap<>();
        map.put("openid",openid);
        List<XstWxUser> xstWxUsers = xstWxUserDao.selectByMap(map);
        BoundValueOperations<String, Object> user = redisTemplate.boundValueOps(openid);
        user.set(xstWxUsers);
        return count;
    }

}

